<template>
	<view class="baseForm">
		<u--form labelPosition="left" labelWidth="120px" style="margin-left: 15px;">
			<u-form-item label="扫描物料条形码">
				<!-- 条码录入 -->
				<scan-bar id="scanInput" ref="scanBarRef" @code-scanned="getScanResult" style="width: 170px;" :key="datekey"></scan-bar>
			</u-form-item>
		</u--form>
		<!-- 搜索信息 -->
		<view class="search">
			<u-input placeholder="请输入存货编码" border="surround" style="width: 170px; height: 18px;"
				v-model="materialCode"></u-input>
			<u-button text="查询" style="width: 80px; height: 32px;margin-left: 60px;"
				@click="select(materialCode)"></u-button>
		</view>
		<!-- tab-bar切换 -->
		<view class="tab-bar">
			<u-tabs :current="activeTab" :list="tabList" :scrollable="false" :activeStyle="{
					color: '#000',
					fontWeight: 'bold',
					transform: 'scale(1.04)'
				}" lineWidth="50px" lineHeight="2px" lineColor="#007aff" @change="changeTab"></u-tabs>
		</view>


		<!-- 待上线信息 -->
		<view v-if="activeTab === 0" class="activeHeight">
			<!-- 列表 -->
			<u-list @scrolltolower="scrolltolower" class="list" v-if="total" :height="listHeight"
				lowerThreshold="100px">
				<u-list-item v-for="(item, index) in tableList" :key="item.id" @click="selectWorkOrder(item,index)">
					<view class="card1">
						<view class="" style="display: flex;justify-content: center;align-items: center;">
							<view class="title2">条码:</view>
							<view class="title1" style="width: 100%;white-space: wrap; word-break: break-all;">
								{{ item?.materialBarcode || '' }}
							</view>
						</view>
						<view class="body1">物料：{{ item?.materialCode || '' }} - {{ item?.materialName || '' }}</view>
						<view style="width: 100%;display: flex;">
							<view class="right">
								<view class="body">件数：{{ item?.materialQuantity || '0' }}</view>
								<view class="body">到货日期：{{ item?.createTime || '待定' }}</view>
							</view>
							<view class="left">
								<view class="body" style="text-align:center;">数量单位：{{ item?.quantityUnit || '待定' }}
								</view>
								<button v-show="item?.isUse==0" class="uni-btn" size="mini" type="success">上线</button>
							</view>
						</view>
					</view>
				</u-list-item>
			</u-list>
			<!-- 空数据 -->
			<view v-else>
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>

		<!-- 已上线信息 -->
		<view v-else class="activeHeight">
			<!-- 列表 -->
			<u-list @scrolltolower="finishScrolltolower" class="list" v-if="finishTotal" :height="listHeight"
				lowerThreshold="100px">
				<u-list-item v-for="(item, index) in finishTableList" :key="item.id">
					<view class="card1">
						<view class="" style="display: flex;justify-content: center;align-items: center;">
							<view class="title2">条码:</view>
							<view class="title1" style="width: 100%;white-space: wrap; word-break: break-all;">
								{{ item?.materialBarcode || '' }}
							</view>
						</view>
						<view class="body1">物料：{{ item?.materialCode || '' }} - {{ item?.materialName || '' }}</view>
						<view style="width: 100%;display: flex;">
							<view class="right">
								<view class="body">件数：{{ item?.materialQuantity || '0' }}</view>
								<view class="body">到货日期：{{ item?.createTime || '待定' }}</view>
							</view>
							<view class="left">
								<view class="body" style="text-align:center;">数量单位：{{ item?.quantityUnit || '待定' }}
								</view>
								<button v-show="item?.isUse==1" class="uni-btn" size="mini" type="primary">已上线</button>
							</view>
						</view>
					</view>
				</u-list-item>
			</u-list>
			<!-- 空数据 -->
			<view v-else>
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>

		<u-modal :show="showImport" ref="uModal" :content="`当前条码为:${selectOrder?.materialBarcode ?? ''}, 请确认是否上线？`"
			confirmText="确认" showCancelButton @cancel="cancelImport" @confirm="confirmImport"
			style="word-break: break-all;"></u-modal>
		<u-modal :show="showImport1" ref="uModal"
			:content="`当前条码为:${selectOrder1?.materialBarcode ?? ''}, 请确认是否上线至${loginWorkInfo.workCenterCode}工作中心？`"
			confirmText="确认" showCancelButton @cancel="cancelImport1" @confirm="confirmImport1"
			style="word-break: break-all;"></u-modal>
		<u-modal :show="showImport2" ref="uModal"
			:content="`当前上线物料批次：${selectOrder2?.materialBatch},与选择的批次加工单批次：${workOrderList[0].planBatch}不同,是否确认上线?`"
			confirmText="确认" showCancelButton @cancel="cancelImport2" @confirm="confirmImport2"
			style="word-break: break-all;"></u-modal>
	</view>
</template>

<script lang="ts" setup>
	import { computed, nextTick, ref, toRaw, watch } from 'vue';
	import { onLaunch, onShow, onPullDownRefresh } from '@dcloudio/uni-app';
	import ScanBar from '@/components/scan-bar/index.vue';
	import { http } from '@/utils/http';
	import { useUserStore } from '../../../stores/useUserStore';
	import { PageResult } from '../../../types/type';
	import { useProduceStore } from '../../../stores/useProduceStore';
	import { useDictionaryStore } from '../../../stores/useDictionaryStore';
	// 获取扫码结果
	function getScanResult(result) {
		console.log('扫码结果', result);
		scanBarRef.value.reset();
		datekey.value = new Date();
		if (!workOrderList.value[0]?.id) {
			uni.$u.toast('请选择加工单！');
			return
		}
		if (result) {
			addWorkOrder(null, result)
		}
	}

	// tab切换功能
	interface TabInfo {
		index : number;
		name ?: string;
	}
	//扫码清除
	const scanBarRef = ref();
	const datekey = ref(new Date());
	//物料编码搜索
	const materialCode = ref('')

	const activeTab = ref(0);
	const tabList = [{ name: '待上线' }, { name: '已上线' }];
	function changeTab(val : TabInfo) {
		activeTab.value = val.index;
		console.log(val.index === 1);
		if (val.index === 0) {
			current.value = 0;
			tableList.value = [];
			loadmore()
		} else if (val.index === 1) {
			finishCurrent.value = 0;
			finishTableList.value = []
			finishLoadmore()
		}
	}
	//查询
	function select(code) {
		materialCode.value = ''
		if (activeTab.value === 0 && code != '') {
			current.value = 0;
			tableList.value = []
			loadmore(null, code);
		} else if (activeTab.value === 1 && code != '') {
			finishCurrent.value = 0;
			finishTableList.value = []
			finishLoadmore(null, code);
		}
	}
	// 登录工作组信息
	const loginWorkInfo = computed(() => JSON.parse(useUserStore().loginWorkInfo));
	// 加工单信息
	const workOrderList : any = computed(() => JSON.parse(useProduceStore().workOrderList));
	console.log("workOrderList", workOrderList.value)
	// 待上线数据
	const tableList = ref([]);
	const current = ref(0);
	const totalPage = ref(0);
	const total = ref(0);

	// 已完成数据
	const finishTableList = ref([]);
	const finishCurrent = ref(0);
	const finishTotalPage = ref(0);
	const finishTotal = ref(0);

	//列表高度
	const listHeight = ref('');

	// 已上线列表获取
	async function finishLoadmore(type ?: string, code ?: string) {
		try {
			finishCurrent.value += 1;
			const result : PageResult<any> = await http({
				method: 'POST',
				url: '/mes/mesproducingstock/queryByPage',
				data: {
					current: finishCurrent.value,
					size: 20,
					data: {
						workCenterId: loginWorkInfo.value.workCenterId,
						isUse: 1,
						materialQuantity: 0,
						materialCode: code,
					}
				}
			});
			const list = result.data
			for (let i = 0; i < list.length; i++) {
				finishTableList.value.push(list[i]);
			}
			finishTableList.value.forEach(item => {
				if (Number(item.quantityUnit) && !isNaN(Number(item.quantityUnit))) {
					item.quantityUnit = useDictionaryStore().filterDictName("MeasurementUnit", item.quantityUnit)
				}
			})
			finishTotalPage.value = result.page;
			finishTotal.value = result.total;
			type === 'refresh' && uni.stopPullDownRefresh();
		} catch (e) {
			console.log(e);
		}
	}

	onShow(() => {
		// #ifdef H5
		listHeight.value = 'calc(100vh - 88px)';
		// #endif

		// #ifdef APP-PLUS
		listHeight.value = 'calc(100vh - 44px)';
		// #endif
		current.value = 0;
		tableList.value = [];
		loadmore();
	});

	onPullDownRefresh(() => {
		current.value = 0;
		tableList.value = [];
		finishCurrent.value = 0;
		finishTableList.value = []
		loadmore('refresh');
		finishLoadmore('refresh');
	});
	//待上线列表
	async function loadmore(type ?: string, code ?: string) {
		try {
			current.value += 1;
			const result : PageResult<any> = await http({
				method: 'POST',
				url: '/mes/mesproducingstock/queryByPage',
				data: {
					current: current.value,
					size: 20,
					data: {
						workCenterId: loginWorkInfo.value.workCenterId,
						isUse: 0,
						isValid: 1,
						materialQuantity: 0,
						materialCode: code,
					}
				}
			});
			const list = result.data
			for (let i = 0; i < list.length; i++) {
				tableList.value.push(list[i]);
			}
			tableList.value.forEach(item => {
				if (Number(item.quantityUnit) && !isNaN(Number(item.quantityUnit))) {
					item.quantityUnit = useDictionaryStore().filterDictName("MeasurementUnit", item.quantityUnit)
				}
			})
			totalPage.value = result.page;
			total.value = result.total;
			type === 'refresh' && uni.stopPullDownRefresh();
		} catch (e) {
			console.log(e);
		}
	}
	const scrolltolower = () => {
		totalPage.value > current.value && loadmore();
	};

	const finishScrolltolower = () => {
		finishTotalPage.value > finishCurrent.value && finishLoadmore();
	};

	// 选择订单
	const selectOrder = ref({});
	const selectIndex = ref();
	const showImport = ref(false);
	function selectWorkOrder(row, index) {
		console.log(row.workCenterId)
		console.log(loginWorkInfo.value.workCenterId)
		selectOrder.value = row;
		selectOrder1.value = row;
		selectOrder2.value = row;
		selectIndex.value = index;
		if (!(selectOrder.value.stockFrom == 1 && selectOrder.value.materialBatch != workOrderList.value[0].planBatch) &&
			!(selectOrder.value.workCenterId != loginWorkInfo.value.workCenterId)) {
			showImport.value = true;
			return;
		} else if ((selectOrder.value.stockFrom == 1 && selectOrder.value.materialBatch != workOrderList.value[0].planBatch) && !(selectOrder.value.workCenterId != loginWorkInfo.value.workCenterId)) {
			showImport2.value = true;
			return;
		} else if ((selectOrder.value.workCenterId != loginWorkInfo.value.workCenterId) && !(selectOrder.value.stockFrom == 1 && selectOrder.value.materialBatch != workOrderList.value[0].planBatch)) {
			showImport1.value = true;
			return;
		}
	}

	// 取消选择订单
	function cancelImport() {
		showImport.value = false;
		selectOrder.value = {};
		selectIndex.value = null;
	}
	// 选择订单
	const selectOrder1 = ref({});
	const showImport1 = ref(false);

	// 点击待上线提交至上线
	async function confirmImport1() {
		showImport1.value = false;
		if (!workOrderList.value[0]?.id) {
			uni.$u.toast('请选择加工单！');
			return
		}

		const res = await http({
			method: 'POST',
			url: "/mes/mesproducingstock/toFeedingNew",
			data: {
				materialBarcode: selectOrder1.value.materialBarcode,
				workCenterId: loginWorkInfo.value.workCenterId,
				workCenterCode: loginWorkInfo.value.workCenterCode,
				workCenterName: loginWorkInfo.value.workCenterName,
			}
		});
		if (res.code == "200") {
			uni.showToast({
				title: '上线成功'
			});
			current.value = 0;
			tableList.value = [];
			loadmore();
			return;
		}
		current.value = 0;
		tableList.value = [];
		loadmore()
	}
	// 取消选择订单
	function cancelImport1() {
		showImport1.value = false;
		selectOrder1.value = {};
	}
	
	// 不同批次
	const selectOrder2 = ref({});
	const showImport2 = ref(false);
	async function confirmImport2() {
		showImport2.value = false;
		if ((selectOrder.value.workCenterId != loginWorkInfo.value.workCenterId)
			&& !(selectOrder.value.stockFrom == 1 && selectOrder.value.materialBatch != workOrderList.value[0].planBatch)) {
			showImport1.value = true;
			return;
		}
		await addWorkOrder(selectOrder.value.id, null);
	}
	// 取消选择订单
	function cancelImport2() {
		showImport2.value = false;
		selectOrder2.value = {};
	}
	//待上线-已上线
	async function addWorkOrder(id ?: string, result ?: string) {
		if (!workOrderList.value[0]?.id) {
			uni.$u.toast('请选择加工单！');
		}
		let returnBarcode = "";
		if (id) {
			returnBarcode = selectOrder.value.materialBarcode
			const res = await http({
				method: 'POST',
				url: '/mes/mesmaterialreturn/getList',
				data: {
					returnBarcode: returnBarcode,
					isReturn: 0
				}
			});
			if (res.data.length > 0) {
				uni.$u.toast('该包装物料正在退货无法上线！');
				return
			}
		}
		if (result) {
			const res = await http({
				method: 'POST',
				url: '/mes/mesmaterialreturn/getList',
				data: {
					returnBarcode: result,
					isReturn: 0
				}
			});
			if (res.data.length > 0) {
				uni.$u.toast('该包装物料正在退货无法上线！');
				return
			}
			//查询其他工作中心物料
			const res1 = await http({
				method: 'POST',
				url: '/mes/mesproducingstock/getList',
				data: {
					materialBarcode: result,
					isValid: 1,
					materialQuantity: 0,
				}
			});
			if (res1.data.length == 0) {
				uni.$u.toast('未找到该条码物料，或者包装数量为0');
				return
			}
			if (res1.data[0].isUse == 1) {
				uni.$u.toast('物料上线失败，已经上线过的不能重复上线。');
				return
			}
			if (res1.code == "200" && res1.data.length > 0 && res1.data[0].stockFrom == 1 && res1.data[0].materialBatch != workOrderList.value[0].planBatch) {
				console.log("当前上线物料与选择的批次加工单批次不同是否确认上线？")
				selectOrder2.value = res1.data[0]
				selectOrder1.value = res1.data[0]
				showImport2.value = true;
				// if (res1.code == "200" && res1.data.length > 0 && res1.data[0].workCenterId != loginWorkInfo.value.workCenterId) {
				// 	console.log("其他工作中心物料上线")
				// 	selectOrder1.value = res1.data[0]
				// 	showImport1.value = true;
				// 	return;
				// }
				return;
			}
			if (res1.code == "200" && res1.data.length > 0 && res1.data[0].workCenterId != loginWorkInfo.value.workCenterId) {
				console.log("其他工作中心物料上线")
				selectOrder1.value = res1.data[0]
				showImport1.value = true;
				return;
			}
		}
		new Promise(async (resolve, reject) => {
			const res = await http({
				method: 'POST',
				url: "/mes/mesproducingstock/toFeeding",
				data: {
					materialBarcode: result,
          workingFormId: workOrderList.value[0].id,
          plannedBatchId: workOrderList.value[0].id,
					id: id,
					routingAllocationId:workOrderList.value[0].routingAllocationId
				}
			});
			if (res.code == "200") {
				uni.showToast({
					title: '上线成功'
				});
			}
			current.value = 0;
			tableList.value = [];
			loadmore();
		});

	}
	// 点击待上线提交至上线
	async function confirmImport() {
		showImport.value = false;
		if (!workOrderList.value[0]?.id) {
			uni.$u.toast('请选择加工单！');
			return
		}
		if(selectOrder.value.stockFrom == 1 && selectOrder.value.materialBatch != workOrderList.value[0].planBatch){
			selectOrder2.value = selectOrder.value
			selectOrder1.value = selectOrder.value
			showImport2.value = true;
			return;
		}
		await addWorkOrder(selectOrder.value.id, null);
	}
</script>

<style lang="scss" scoped>
	.baseForm {
		.tab-bar {
			padding: 0 40px;
		}

		.upload-scan {
			padding: $uni-page-padding;
			padding-top: 5px;
			padding-bottom: 5px;
		}

		.u-line {
			padding: 10px 0;
		}

		.search {
			display: grid;
			padding: $uni-page-padding;

			grid-template-columns: 335rpx 335rpx;
			grid-column-gap: 20rpx;
			grid-row-gap: 20rpx;

			.u-input {
				border: 1px solid rgba(214, 215, 217, 0.6);
			}
		}
	}

	.list {
		.card {
			margin: $uni-page-padding;
			margin-top: 5px;
			margin-bottom: 5px;
			border-radius: 7px;
			display: flex;
			align-items: center;
			padding: 12px 10px 0px 10px;
			transition: all 300ms ease;
			box-shadow: 0 1px 5px rgba(19, 11, 236, 0.13);
			background-color: #fff;
			display: flex;
			align-items: flex-start;

			.left {
				flex: 1;
			}

			.title {
				font-size: 12px;
				line-height: 40px;
				height: 40px;
				margin-bottom: 8px;
				font-weight: 700;
				color: #101010;
				// width: 160px;
				// border-bottom: 1px solid #E5EBFF;
			}


			.uni-btn {
				float: right;
				font-size: 12px;
				height: 24px;
				line-height: 24px;
				padding: 0 15px;
				margin-top: 7px;
				font-weight: 400;
			}

			.des {
				font-size: 12px;
				line-height: 20px;
				height: 20px;
				margin-bottom: 3px;
			}

			.right {
				// flex: 1;
				flex-basis: calc(60% + 10px);
			}
		}

		.card1 {
			margin: $uni-page-padding;
			margin-top: 5px;
			margin-bottom: 5px;
			border-radius: 7px;
			align-items: center;
			padding: 12px 10px 0px 10px;
			transition: all 300ms ease;
			box-shadow: 0 1px 5px rgba(19, 11, 236, 0.13);
			background-color: #fff;
			align-items: flex-start;

			.left {
				flex: 1;
				text-align: right;
				font-size: 13px;
				vertical-align: bottom;
			}

			.title {
				font-size: 12px;
				line-height: 40px;
				height: 40px;

				font-weight: 700;
				color: #101010;
				// width: 160px;
				// border-bottom: 1px solid #E5EBFF;
			}

			.title1 {
				font-size: 12px;
				margin-bottom: 5px;
				font-weight: 700;
				color: #101010;
				width: 160px;
				// border-bottom: 1px solid #E5EBFF;
			}

			.title2 {
				font-size: 12px;
				margin-bottom: 5px;
				font-weight: 700;
				color: #101010;
				width: 40px;
				// border-bottom: 1px solid #E5EBFF;
			}

			.uni-btn {
				float: right;
				font-size: 12px;
				height: 24px;
				line-height: 24px;
				padding: 0 15px;
				margin-top: 7px;
				font-weight: 400;
			}

			.des {
				font-size: 12px;
				line-height: 20px;
				height: 20px;
				margin-bottom: 3px;
			}

			.right {
				// flex: 1;
				flex-basis: calc(60% + 10px);

				.body {
					font-size: 12px;
					line-height: 20px;
					height: 20px;
					margin-bottom: 3px;

					.span {
						width: 50%;
						// text-align: left;
						display: inline-block;
					}
				}
			}

			.body1 {
				font-size: 12px;
				line-height: 20px;
				height: 20px;
				margin-bottom: 3px;

				.span {
					width: 50%;
					// text-align: left;
					display: inline-block;
				}
			}
		}
	}
</style>